package com.zzu.base.config;

import com.zzu.base.filter.JwtAuthenticationTokenFilter;
import com.zzu.base.handler.AccessDeniedExceptionHandler;
import com.zzu.base.handler.AuthenticationExceptionHandler;
import com.zzu.base.handler.PermissionHandler;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler;
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

@EnableMethodSecurity
@Configuration
public class SecurityConfig {

    @Resource
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Resource
    private AuthenticationExceptionHandler authenticationExceptionHandler; // 认证异常处理器

    @Resource
    private AccessDeniedExceptionHandler accessDeniedExceptionHandler; // 授权异常处理器

    // 密码加密器
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    // 认证管理器（替代旧版的 AuthenticationManagerBuilder）
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }
    @Bean
    public MethodSecurityExpressionHandler methodSecurityExpressionHandler(PermissionHandler permissionHandler) {
        DefaultMethodSecurityExpressionHandler expressionHandler =
                new DefaultMethodSecurityExpressionHandler();
        expressionHandler.setPermissionEvaluator(permissionHandler); // 设置自定义评估器
        return expressionHandler;
    }
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .cors(cors -> cors.configurationSource(corsConfigurationSource()))
                // 1. 禁用 CSRF（REST API 场景）
                .csrf(AbstractHttpConfigurer::disable)

                // 2. 配置会话管理（无状态，基于 JWT）
                .sessionManagement(session -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                )

                // 3. 配置 URL 权限规则
                .authorizeHttpRequests(authorize -> authorize
                        // 放行公开接口
                        .requestMatchers(
                                "/**",
                                "/doc.html",
                                "/druid/**",
                                "/avatar/**",
                                "/webjars/**",
                                "/v3/**",
                                "/swagger-resources/**",
                                "/auth/**",           // 登录/注册接口
                                "/favicon.ico"        // 图标
                        ).permitAll()
                        // 其他请求必须认证
                        .anyRequest().authenticated()
                )

                // 4. 配置异常处理（认证/授权失败）
                .exceptionHandling(exception -> exception
                        .authenticationEntryPoint(authenticationExceptionHandler)  // 401 异常
                        .accessDeniedHandler(accessDeniedExceptionHandler)        // 403 异常
                );

        // 5. 添加 JWT 过滤器（在用户名密码过滤器之前执行）
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }
    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();

        // 设置允许跨域请求的域名（等效于 allowedOriginPatterns("*")）
        config.setAllowedOriginPatterns(Arrays.asList("*"));

        // 是否允许 Cookie（等效于 allowCredentials(true)）
        config.setAllowCredentials(true);

        // 设置允许的请求方式（等效于 allowedMethods("GET", "POST", "DELETE", "PUT")）
        config.setAllowedMethods(Arrays.asList("GET", "POST", "DELETE", "PUT"));

        // 设置允许的 Header 属性（等效于 allowedHeaders("*")）
        config.setAllowedHeaders(Arrays.asList("*"));

        // 跨域允许时间（等效于 maxAge(3600)）
        config.setMaxAge(3600L);

        // 对所有路径应用此 CORS 配置
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);

        return source;
    }
}